package com.zhongkeruan.user.service.impl;

import com.codingapi.tx.annotation.TxTransaction;
import com.zhongkeruan.common.constants.StatusCode;
import com.zhongkeruan.common.model.Order;
import com.zhongkeruan.common.model.User;
import com.zhongkeruan.common.vo.Result;
import com.zhongkeruan.user.annotation.DS;
import com.zhongkeruan.user.dao.UserDao;
import com.zhongkeruan.user.exception.TimeOutException;
import com.zhongkeruan.user.hystrix.OrderHystrix;
import com.zhongkeruan.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author yangyao
 * @Description: UserServiceImpl
 * @date 2019/1/11 15:13
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderHystrix orderHystrix;

    @DS("dataSource2")
    @Transactional(readOnly = true)
    public List<User> getUserList() throws Exception{
        List<User> userList = (List<User>) redisTemplate.opsForValue().get("user_all");
        if (userList == null){
            userList = userDao.getUserList();
            redisTemplate.opsForValue().set("user_all",userList);
        }
        return userList;
    }

    @Transactional
    public User getUserById(Long id) throws  Exception{
        User user = userDao.getUserById(id);
        return user;
    }

    public User findByUserName(String userName) throws Exception {
        return userDao.findByUserName(userName);
    }

    @Transactional
    @TxTransaction(isStart = true)
    public int addUser(User user) throws Exception {
        Order order = new Order();
        order.setOrderDate(new Date());
        order.setProductId(2L);
        order.setUserId(2L);
        order.setProductNum(2);
        order.setTotalAmount(new BigDecimal(3));
        order.setOrderDate(new Date());
        Result result= orderHystrix.addOrder(order);
        if (StatusCode.SUCCESS != result.getCode()){
            throw  new TimeOutException(StatusCode.TIMEOUT,"请求超时");
        }
       // int a = 1/0;
        return userDao.addUser(user);
    }


}
